// src/components/Table/hooks/useDataSource.ts

import { ref, ComputedRef, unref, computed, onMounted, watchEffect, watch } from 'vue';
import type { BasicTableProps } from '../types/table';
import type { PaginationProps } from '../types/pagination';
import { isBoolean, isFunction, isArray } from '@/utils/is';
import { APISETTING } from '../const';

// 🌟 1. (重要) 确保 APISETTING 中的字段名与你的后端 API 返回的字段名完全一致
// 如果你的 APISETTING.ts 文件中的值不同，请务必在那里修改！
// 这里我们假设它已经被正确配置为：
// {
//   pageField: 'page',
//   sizeField: 'size',
//   totalField: 'pageCount', // 总页数
//   listField: 'items',     // 数据列表
//   countField: 'total'     // 总条数
// }

export function useDataSource(
  propsRef: ComputedRef<BasicTableProps>,
  { getPaginationInfo, setPagination, setLoading, tableData },
  emit
) {
  const dataSourceRef = ref<Recordable[]>([]);

  watchEffect(() => {
    tableData.value = unref(dataSourceRef);
  });

  watch(
    () => unref(propsRef).dataSource,
    () => {
      const { dataSource }: any = unref(propsRef);
      dataSource && (dataSourceRef.value = dataSource);
    },
    {
      immediate: true,
    }
  );

  const getRowKey = computed(() => {
    const { rowKey }: any = unref(propsRef);

    if (rowKey) {
      if (isFunction(rowKey)) {
        return (record: Recordable, index: number) => {
          const result = rowKey(record, index);
          return result ?? `row-${index}`;
        };
      }
      if (typeof rowKey === 'string') {
        return (record: Recordable, index: number) => {
          const result = record[rowKey];
          return result ?? `row-${index}`;
        };
      }
    }

    return (record: Recordable, index: number) => {
      return record.id ?? `row-${index}`;
    };
  });

  const getDataSourceRef = computed(() => {
    // 这个计算属性有点多余，但我们保持它以兼容现有代码
    return unref(dataSourceRef);
  });

  async function fetch(opt?) {
    try {
      setLoading(true);
      const { request, pagination, beforeRequest, afterRequest }: any = unref(propsRef);
      if (!request) return;

      // 组装分页信息
      const pageField = APISETTING.pageField;
      const sizeField = APISETTING.sizeField;
      const totalField = APISETTING.totalField; // 总页数
      const listField = APISETTING.listField; // 数据列表
      const countField = APISETTING.countField; // 总条数

      let pageParams = {};
      const { page = 1, pageSize = 10 } = unref(getPaginationInfo) as PaginationProps;

      // 如果分页被禁用，则不传递分页参数
      if ((isBoolean(pagination) && !pagination) || isBoolean(getPaginationInfo)) {
        pageParams = {};
      } else {
        pageParams[pageField] = (opt && opt[pageField]) || page;
        pageParams[sizeField] = pageSize;
      }

      let params = {
        ...pageParams,
        ...opt,
      };

      if (beforeRequest && isFunction(beforeRequest)) {
        params = (await beforeRequest(params)) || params;
      }

      const res = await request(params);

      // 🌟 3. 从响应中解析数据
      const resultList = res[listField] || []; // 使用配置的字段名获取数据列表
      const resultTotalCount = res[countField] || 0; // 总条数
      const resultPageCount = res[totalField] || 0; // 总页数
      const currentPage = res[pageField] || page; // 当前页

      // 如果数据为空但当前页码大于1，尝试获取第一页数据
      if (resultList.length === 0 && currentPage > 1) {
        setPagination({ page: 1 });
        return await fetch({ ...opt, [pageField]: 1 });
      }

      // 如果提供了 afterRequest 钩子，允许用户修改数据
      let finalList = resultList;
      if (afterRequest && isFunction(afterRequest)) {
        finalList = (await afterRequest(finalList)) || finalList;
      }

      // 更新数据源
      dataSourceRef.value = finalList;

      // 🌟 4. 更新分页信息
      setPagination({
        page: currentPage,
        pageCount: resultPageCount,
        itemCount: resultTotalCount,
      });

      // 如果是通过 opt 手动指定页码，也更新 pagination
      if (opt && opt[pageField]) {
        setPagination({
          page: opt[pageField] || 1,
        });
      }

      emit('fetch-success', {
        items: finalList,
        total: resultTotalCount,
      });
    } catch (error) {
      console.error(error);
      emit('fetch-error', error);
      dataSourceRef.value = [];
      setPagination({
        pageCount: 0,
        itemCount: 0,
      });
    } finally {
      setLoading(false);
    }
  }

  onMounted(() => {
    // 使用 nextTick 或 setTimeout 确保组件渲染完成后再请求数据
    setTimeout(() => {
      fetch();
    }, 16);
  });

  function setTableData(values) {
    dataSourceRef.value = values;
  }

  function getDataSource(): any[] {
    return getDataSourceRef.value;
  }

  async function reload(opt?) {
    await fetch(opt);
  }

  return {
    fetch,
    getRowKey,
    getDataSourceRef,
    getDataSource,
    setTableData,
    reload,
  };
}
